<template>
	<view class="reserve_container">
		<view class="reserve_date">
			<text>日期</text>
			<view style="display: flex;align-items: center;">
				<uni-datetime-picker type="date" :value="reserveDate" :start="startValue" :end="endValue"
					:clearIcon="false" @change="change" style="z-index: 99;">
					<text style="color: #A4A5A7;">{{reserveDate}}</text>
					<text style="color: #A4A5A7;margin: 0 10rpx;">{{weekValue}}</text>
					<image src="../../../static/img/meeting/arrow-right.png"
						style="width: 16rpx;height: 24rpx; margin-left: 14rpx;"></image>
				</uni-datetime-picker>
			</view>
		</view>
		<view class="reserve_list">
			<view class="reserve_item" v-for="(item,index) in meetingRoomList" :key="index" @click="itemClick(item)">
				<view class="reserve_content">
					<view class="reserve_label">
						<view class="meeting_name">{{item.name}}</view>
						<view class="meeting_num">
							<image src="../../../static/img/meeting/num.png" style="width: 26rpx;height: 26rpx;">
							</image>
							<text>{{item.capacity}}</text>
						</view>
					</view>
					<image :src="item.img" style="width: 134rpx;height: 102rpx;">
				</view>
				<view class="tip_container">
					<view class="tip_list">
						<view class="tip_item" v-for="(items) in item.timeInterval" :key="items.id"
							:style="{backgroundColor: items.state == 0 ? '#fff' : '#ced2d5'}"></view>
					</view>
					<view class="tip_time">
						<view class="time_point" v-for="(items,i) in item.timeInterval" :key="i">
							{{halfhourFilter(items)}}
						</view>
						<!-- 显示最后一个整点值 -->
						<view v-if="item.timeInterval[item.timeInterval.length - 1].id % 2 == 0" class="last_point">
							{{item.timeInterval[item.timeInterval.length - 1].value.split("-")[1].split(":")[0]}}
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 预约弹框 -->
		<u-popup :show="modalFlag" @close="closeModal()" :round="12">
			<view class="modal_top">
				<view class="modal_title">{{detailInfo.name}}</view>
				<view class="modal_num">
					<image src="../../../static/img/meeting/num.png" style="width: 26rpx;height: 26rpx;"></image>
					<text style="margin-left: 10rpx;">{{detailInfo.capacity}}</text>
				</view>
				<view class="modal_address">
					<image src="../../../static/img/meeting/address.png" style="width: 26rpx;height: 26rpx;"></image>
					<view class="address_content">{{detailInfo.address}}</view>
				</view>
			</view>
			<scroll-view class="time_period" scroll-y="true" :enhanced="true" :show-scrollbar="true">
				<u-checkbox-group v-model="timePeriod" placement="column" shape="circle" size="20"
					@change="timePeriodChange">
					<template v-for="(item, index) in timePeriodList">
						<view style="display: flex;align-items: center;">
							<u-checkbox :key="index" :name="item.value" :disabled="item.state != 0"></u-checkbox>
							<view class="period_item">
								<view>{{item.value}}</view>
								<view style="color: #7C8083;">{{ getStateValue(item.state)}}</view>
							</view>
						</view>
					</template>
				</u-checkbox-group>
			</scroll-view>
			<view class="complete_container">
				<view class="complete_left">
					<view>已选择时段：</view>
					<view class="complete_content">
						<view v-for="(item,index) in selectTimeList" :key="index">{{item}}</view>
					</view>
				</view>
				<view class="complete_btn" @click="submit()">确定</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getFutureDate,
		getWeekDate
	} from "../../../utils/dayjs.js"
	import {
		getMeetingList,
		getMeetingInfo,
		addMeetingReserve
	} from "../../../api/meeting.js"
	import {
		mapState,
		mapMutations
	} from 'vuex' // vuex
	export default {
		data() {
			return {
				meetingRoomList: [],
				modalFlag: false,
				reserveDate: getFutureDate(0),
				startValue: getFutureDate(0),
				endValue: getFutureDate(6),
				weekValue: getWeekDate(getFutureDate(0)),
				timePeriod: [],
				detailInfo: {
					title: "",
					num: 0,
					address: "",
				},
				reservedTime: [],
				selectTimeList: [],
				pageParam: {
					pageIndex: 1,
					pageSize: 10
				},
				timePeriodList: [],
				currentMeetingId: ""
			}
		},
		onShow() {
			// token不存在，调小程序登陆接口获取code,通过code获取token
			if (!uni.getStorageSync('token')) {
				this.getInfo()
			}
			this.getList()
		},
		// 下拉刷新
		onPullDownRefresh() {
			uni.showLoading({
				title: '加载中',
			})
			setTimeout(() => {
				this.pageParam.pageIndex = 1
				this.meetingRoomList = []
				this.getList()
				uni.stopPullDownRefresh();
				uni.hideLoading();
			}, 1000)
		},
		methods: {
			// 通过微信code获取token
			getInfo() {
				uni.login({
					provider: 'weixin',
					success: (res) => {
						this.code = res.code
						this.getToken()
					}
				})
			},

			// 获取token
			async getToken() {
				const _that = this
				uni.request({
					url: 'https://wechat.atptest.com:44386/connect/token',
					data: {
						code: _that.code,
						grant_type: 'wechat',
					},
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'Authorization': 'Basic QXBpX1dlYjpBcGlfV2Vi'
					},
					success(res) {
						console.log("App 获取到了token");
						_that.setToken(res.data.access_token);
						_that.getList();
					}
				})
			},

			async getList() {
				const res = await getMeetingList({
					time: this.reserveDate
				})
				if (res) {
					this.meetingRoomList = res
				} else {
					this.meetingRoomList = []
				}
			},

			//过滤半小时的时间
			halfhourFilter(val, index, i) {
				if (val.id % 2 != 0) {
					return Number(val.value.split("-")[0].split(":")[0])
				} else {
					return ""
				}
			},

			//切换日期
			change(val) {
				this.reserveDate = val;
				this.weekValue = getWeekDate(val);
				this.getList()
			},

			//点击会议室预约
			async itemClick(val) {
				this.modalFlag = true
				this.currentMeetingId = val.id
				const res = await getMeetingInfo({
					roomId: val.id,
					time: this.reserveDate
				})
				if (res) {
					this.detailInfo.name = res.name
					this.detailInfo.capacity = res.capacity
					this.detailInfo.address = res.address
					this.timePeriodList = res.timeInterval
					this.timePeriod = this.timePeriodList.map(item => {
						if (item.state != 0) {
							return item.value
						} else {
							return ""
						}
					}).filter(it => {
						return it != ""
					})
					this.reservedTime = this.timePeriod
				}
				this.selectTimeList = []
			},

			// 调起通知
			subscribe() {
				const _that = this
				uni.getSetting({
					withSubscriptions: true,
					success: (res) => {
						if (!res.subscriptionsSetting.mainSwitch) {
							uni.showModal({
								title: '提示',
								content: '为了及时获取会议室预约信息，您是否想接收会议室预约的消息提醒？',
								success: function(res) {
									if (res.confirm) {
										// 订阅消息的总开关,如果是关着的，引导用户去打开
										_that.openMessage()
									} else if (res.cancel) {
										//上传表单信息
										_that.confirmSubmit();
									}
								}
							});
						} else {
							// 如果开着，则继续向下打开弹窗，获取用户授权，调用通知
							_that.message()
						}
					},
					fail() {
						// 如果失败，也打开弹窗，获取用户授权，调用通知
						_that.message()
					}
				})
			},

			// 调用通知
			message() {
				const _that = this
				uni.requestSubscribeMessage({
					//此处填写申请的模板ID
					tmplIds: ['UBM3PCWkuzTt9yEtbBnXT_JtTMG5R6zwOlWcX_m3pKA'],
					success(res) {
						console.log("调用通知");
						//上传表单信息
						_that.confirmSubmit();
					},
					fail(res) {
						console.log(res);
					}
				})
			},

			// 引导用户开启订阅
			openMessage() {
				const _that = this
				uni.openSetting({
					withSubscriptions: true,
					complete: (res) => {
						//上传表单信息
						_that.confirmSubmit();
					}
				})
			},

			// 提交预约
			async confirmSubmit() {
				let req = {
					roomId: this.currentMeetingId,
					schedule: this.reserveDate,
					scheduleRange: this.selectTimeList
				}
				const res = await addMeetingReserve(req)
				console.log("预约", res);
				if (res) {
					if (!res.code) {
						uni.showToast({
							title: "预约成功",
							icon: "success"
						})
						this.modalFlag = false
						this.getList()
					} else {
						this.itemClick({
							id: this.currentMeetingId
						})
					}
				}
			},

			//点击预约按钮
			async submit() {
				for (let i = 0; i < this.selectTimeList.length; i++) {
					if (i > 0 && this.selectTimeList[i].split("-")[0] != this.selectTimeList[i - 1].split("-")[1]) {
						uni.showToast({
							title: "不能跨时间段",
							icon: "error"
						})
						return
					}
				}
				if (this.selectTimeList.length > 0) {
					this.subscribe()
				} else if (this.timePeriod.length == this.timePeriodList.length) {
					uni.showToast({
						title: "当日已预约完毕",
						icon: "error"
					})
					return
				} else {
					uni.showToast({
						title: "请选择预约时间",
						icon: "error"
					})
				}
			},

			//状态转换成中文
			getStateValue(val) {
				switch (val) {
					case 1:
						return "已被预定"
					case 2:
						return "已过期"
				}
			},

			//时间段选择
			timePeriodChange(val) {
				this.selectTimeList = this.getArrDifference(val, this.reservedTime)
			},

			//获取两个数组中不同的部分
			getArrDifference(arr1, arr2) {
				return arr1.concat(arr2).filter((v, i, arr) => {
					return arr.indexOf(v) === arr.lastIndexOf(v);
				});
			},

			//关闭预约弹框
			closeModal() {
				this.modalFlag = false
			},
		}
	}
</script>

<style lang="scss" scoped>
	.reserve_container {
		width: 100%;
		min-height: 100vh;
		background-color: #F2F1F6;

		.reserve_date {
			width: 100%;
			height: 80rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 24rpx;
			box-sizing: border-box;
			font-size: 28rpx;
			font-weight: 400;
			color: #000;
			background-color: #fff;
			position: fixed;
			top: 0;
			z-index: 99;
		}

		.reserve_list {
			width: 100%;
			padding: 30rpx 20rpx;
			padding-top: 120rpx;
			box-sizing: border-box;

			.reserve_item {
				width: 100%;
				height: 234rpx;
				background: rgb(255, 255, 255);
				border-radius: 20rpx;
				padding: 24rpx 24rpx 12rpx 24rpx;
				box-sizing: border-box;
				margin-bottom: 30rpx;

				.reserve_content {
					display: flex;
					justify-content: space-between;

					.reserve_label {
						display: flex;
						flex-direction: column;
						justify-content: space-between;

						.meeting_name {
							color: rgb(30, 30, 30);
							font-family: 思源黑体;
							font-size: 36rpx;
							font-weight: 500;
						}

						.meeting_num {
							display: flex;
							align-items: center;
							font-size: 28rpx;
							font-weight: 400;
						}
					}
				}

				.tip_container {
					width: 100%;
					margin-top: 32rpx;

					.tip_list {
						width: 100%;
						height: 26rpx;
						display: flex;
						border: 1px solid rgb(164, 165, 167);
						border-right: none;

						.tip_item {
							flex: 1;
							border-right: 1px solid rgb(164, 165, 167);
						}
					}

					.tip_time {
						width: 100%;
						height: 26rpx;
						display: flex;
						color: rgb(164, 165, 167);
						font-family: 思源黑体;
						font-size: 20rpx;
						font-weight: 400;
						position: relative;

						.time_point {
							flex: 1;
							text-align: left;
							margin-top: 10rpx;
							margin-left: -8rpx;
						}

						.last_point {
							flex: 1;
							position: absolute;
							right: -10rpx;
							top: 10rpx;
						}
					}
				}
			}
		}

		.modal_top {
			padding: 28rpx 32rpx;
			box-sizing: border-box;

			.modal_title {
				color: rgb(30, 30, 30);
				font-family: 思源黑体;
				font-size: 36rpx;
				font-weight: 500;
			}

			.modal_num {
				display: flex;
				align-items: center;
				margin: 10rpx 0;
			}

			.modal_address {
				display: flex;
				align-items: center;

				.address_content {
					flex: 1;
					margin-left: 10rpx;
					text-overflow: ellipsis;
					overflow: hidden;
					white-space: nowrap;
				}
			}
		}

		.time_period {
			width: 100%;
			height: 726rpx;
			padding-left: 32rpx;
			box-sizing: border-box;
			border-top: 1px solid rgb(235, 237, 236);
			border-bottom: 1px solid rgb(235, 237, 236);

			.period_item {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;
				height: 106rpx;
				border-bottom: 1px solid rgb(235, 237, 236);
				padding-right: 32rpx;
				box-sizing: border-box;
				color: rgb(51, 51, 51);
				font-family: 思源黑体;
				font-size: 36rpx;
				font-weight: 400;
			}
		}

		.complete_container {
			width: 100%;
			display: flex;
			justify-content: space-between;
			padding: 22rpx 32rpx;
			box-sizing: border-box;

			.complete_left {
				display: flex;
				color: rgb(32, 33, 35);
				font-family: 思源黑体;
				font-size: 30rpx;
				font-weight: 400;
			}

			.complete_btn {
				width: 168rpx;
				height: 76rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				background: rgb(1, 126, 253);
				border-radius: 14rpx;
				color: rgb(255, 255, 255);
				font-family: 思源黑体;
				font-weight: 400;
			}
		}
	}
</style>
<style lang="scss">
	.row {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.center {
		align-items: center;
		justify-content: center;
	}

	.titleItem {
		line-height: 90rpx;
		font-size: 34rpx;
		font-weight: 550;
	}

	::v-deep .u-alert-tips {
		border: none;
	}

	::v-deep .u-alert-desc {
		font-size: 12px;
		color: #fa6400;
	}
</style>